package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;


@RestController
@RequestMapping("/dish")
@Slf4j
public class DishController {

    @Autowired
    private DishService dishService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private CategoryService categoryService;


    /**
     * 添加菜品
     *
     * @param dishDto
     * @return
     */
    @CachePut(value = "dishCache", key = "#dishDto.id")
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto) {
        dishService.saveWithFlavor(dishDto);
        return R.success("添加菜品成功");
    }

    /**
     * 菜品分页查询
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name) {
        //1.菜品基础分页查询
        //分页构造器
        Page<Dish> dishPage = new Page<>(page, pageSize);
        //条件构造器
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        lqw.like(StringUtils.isNotEmpty(name), Dish::getName, name);
        lqw.orderByDesc(Dish::getUpdateTime);
        //查询
        dishService.page(dishPage, lqw);

        //2.处理分页集合查询
        Page<DishDto> dishDtoPage = new Page<>();
        //复制分页信息 排除分页集合数据 因为集合数据没有分类名称
        BeanUtils.copyProperties(dishPage, dishDtoPage, "records");
        //处理集合数据
        List<Dish> records = dishPage.getRecords();
        List<DishDto> dishDtos = new ArrayList<>();
        records.forEach(dish -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(dish, dishDto);
            Category category = categoryService.getById(dish.getCategoryId());
            if (category != null) {
                dishDto.setCategoryName(category.getName());
            }
            dishDtos.add(dishDto);
        });
        dishDtoPage.setRecords(dishDtos);

        return R.success(dishDtoPage);
    }

    /**
     * 根据id 查询菜品数据和对应口味信息
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<DishDto> getById(@PathVariable Long id) {
        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return R.success(dishDto);
    }

    /**
     * 修改菜品
     *
     * @param dishDto
     * @return
     */
    @CacheEvict(value = "dishCache", key = "#dishDto.categoryId")
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto) {
        dishService.updateWithFlavor(dishDto);
        return R.success("修改菜品成功");
    }

    /**
     * 删除菜品 批量和单个
     *
     * @param ids
     * @return
     */
    @CacheEvict(value = "dishCache", key = "#ids")
    @DeleteMapping
    public R<String> delete(@RequestParam List<Long> ids) {
        dishService.deleteWithFlavor(ids);
        return R.success("删除菜品成功");
    }

    /**
     * 改变菜品停售起售状态
     *
     * @param status
     * @param ids
     */
    @PostMapping("/status/{status}")
    public R<String> changeStatus(@PathVariable Integer status, @RequestParam List<Long> ids) {
        dishService.changeStatus(status, ids);
        return R.success("菜品状态修改成功");
    }

    /**
     * 前端页面菜品分类显示
     *
     * @param dish
     * @return
     */
    @Cacheable(value = "dishCache", key = "#dish.categoryId")
    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish) {


        //查询菜品集合
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        lqw.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());
        lqw.eq(Dish::getStatus, 1);
        lqw.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        List<Dish> list = dishService.list(lqw);

        //复制Dish 到dishDto
        List<DishDto> dtoList = new ArrayList<>();
        list.forEach(dto -> {
            //创建一个dishDto对象 复制数据
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(dto, dishDto);
            Long categoryId = dto.getCategoryId();
            Category category = categoryService.getById(categoryId);
            if (category != null) {
                dishDto.setCategoryName(category.getName());
            }
            //查询菜品口味数据
            LambdaQueryWrapper<DishFlavor> qw = new LambdaQueryWrapper<>();
            qw.eq(DishFlavor::getDishId, dto.getId());
            List<DishFlavor> flavorList = dishFlavorService.list(qw);
            dishDto.setFlavors(flavorList);
            dtoList.add(dishDto);
        });

        return R.success(dtoList);
    }

}
